<template>
	<div style="width: 100%; height: 100%; position: relative;">
		<div class="container">
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>快捷选择</span>
				</div>
				<div>
					<el-form ref="form" label-width="100px">
						<el-form-item label="类型分类" prop="type">
							<el-select filterable v-model="convenient_num_value" @change="convenientChange"
								placeholder="请选择类型分类">
								<el-option v-for="(item,n) in convenient_num" :label="item.name"
									:value="n"></el-option>
							</el-select>
						</el-form-item>
					</el-form>

				</div>
			</el-card>
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>壁纸信息</span>
				</div>
				<div>
					<el-form ref="form" :model="form" label-width="100px">
						<el-form-item label="壁纸名称:" prop="name" :rules="[
						      { required: true, message: '壁纸名称不能为空'}]">
							<el-input style="width: 500px;" maxlength="100" show-word-limit
								v-model="form.name"></el-input>
						</el-form-item>
						<el-form-item label="类型分类" prop="type">
							<el-select v-model="form.type" placeholder="请选择类型分类">
								<el-option v-for="(item,n) in types" :label="item.name" :value="item._id"></el-option>
							</el-select>
						</el-form-item>
					</el-form>

				</div>
			</el-card>
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>选择壁纸标签</span>
				</div>
				<div>
					<!-- <el-select v-model="form.tags" multiple placeholder="请选择">
						<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select> -->
				</div>
				<div class="select-tag">
					<el-tag :key="n" v-for="(tag,n) in form.tags" closable :disable-transitions="false"
						@close="handleClose(tag)">
						{{tag.name}}
					</el-tag>
					<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
						size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
					</el-input>
					<el-button v-else class="button-new-tag" size="small" @click="showInput">+ 标签</el-button>
				</div>
			</el-card>
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>上传壁纸</span>
				</div>
				<div>
					<ul class="ny-upload-ul">
						<li v-for="(itam,i) in shrinkArr">
							<div>
								<img :src="itam.url" alt="" />
								<span class="ny-upload-span">
									<span @click="handlePictureCardPreview()" class="ny-upload-span-itam1"><i
											class="el-icon-zoom-in"></i></span>
									<span @click="deleteImg(i)" class="ny-upload-span-itam2"><i
											class="el-icon-delete"></i></span>
								</span>
							</div>
						</li>
					</ul>
					<div class="ny-upload-img" @click="uploaD">
						<i data-v-293d3606 class="el-icon-plus"></i>
					</div>
					<el-dialog :visible.sync="dialogVisible">
						<img width="100%" :src="shrink_url.url" alt="">
					</el-dialog>
				</div>
			</el-card>
		</div>
		<!-- 提交 -->
		<div class="ny-from-primary">
			<div class="ny-from-primary-box">
				<el-button @click="uploadAllimg" type="success">上传图片</el-button>
				<el-button @click="onSubmits" type="primary">提交</el-button>
				<el-button>取消</el-button>
			</div>
		</div>
		<!-- 历史记录 -->
		<div class="history">
			<div class="history-title">
				历史记录
			</div>
			<div class="history-cont">
				<img :key="m" v-for="(n,m) in shrink_url_num" :src="n" alt="" srcset="" />
			</div>
		</div>

	</div>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					name: '',
					create_date: '',
					down: 0,
					img_url: '',
					shrink_url: '',
					tags: [],
					type: "",
					img_cd: 2,
				},
				convenient_num_value: '',
				types: [],
				convenient_num: [],
				inputVisible: false,
				inputValue: '',
				dynamicTags: [],
				options: [],
				dialogVisible: false,
				img_url: {
					name: '',
					url: ''
				},
				shrink_url: {
					name: '',
					url: ''
				},
				shrink_url_num: [], //缩率图数组，历史记录
				isimg_url: false,
				isshrink_url: false,

				imgArr: [],
				shrinkArr: [],
				imageArr: [],
				istrue: false, //检查是否上传图片

			};
		},
		created() {
			let that = this
			let col = uniCloud.importObject('ny102Type', {
				customUI: true
			})
			col.getTypes().then(res => {
				console.log(res)
				that.types = res.data
			})
			this.pictureQuery()
			let col1 = uniCloud.importObject('ny102AddPictureConvenient', {
				customUI: true
			})
			col1.getConvenient().then(res => {
				console.log(res.data)
				that.convenient_num = res.data.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
				console.log(this.convenient_num)
			})
		},
		methods: {
			convenientChange(e) {
				this.form.tags = this.convenient_num[e].tags
				this.form.name = this.convenient_num[e].name
				this.form.type = this.convenient_num[e].type
				console.log(e)
			},
			deleteImg(i) {
				console.log(i)
				this.shrinkArr = this.shrinkArr.filter((a, j) => j != i)
				this.imgArr = this.imgArr.filter((a, j) => j != i)
			},
			//上车所有图片
			uploadAllimg() {
				if (this.istrue == false) {
					let that = this
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					});
					this.shrink_url_num = [...that.shrinkArr, ...this.shrink_url_num, ]
					//上传所有缩率图片
					function simulateAsyncEvent(item) {
						let that = this
						return new Promise((resolve) => {
							uniCloud.uploadFile({
								filePath: item.url, //要上传的文件对象
								cloudPath: `ny102/pictureAll/shrinkage/${item.name}.jpeg`,
								cloudPathAsRealPath: true,
								success(res) {
									let imageUrl = res.fileID //云端返回的图片地址
									console.log('imageUrl', imageUrl)
									resolve();
								},
								fail(err) {
									console.log(err)
								},
								complete() {
									uni.hideLoading()
								}
							});

						});
					}
					async function asyncLoop(items) {
						for (const item of items) {
							console.log(item)
							await simulateAsyncEvent(item);
						}
					}
					asyncLoop(that.shrinkArr)
					//上传所有图片
					function simulateAsyncEvent1(item) {

						return new Promise((resolve) => {
							uniCloud.uploadFile({
								filePath: item.url, //要上传的文件对象
								cloudPath: `ny102/pictureAll/lossless/${item.name}.${item.type}`,
								cloudPathAsRealPath: true,
								success(res) {
									let imageUrl = res.fileID //云端返回的图片地址
									resolve();
								},
								fail(err) {
									console.log(err)
								},
								complete() {
									uni.hideLoading()
								}
							});

						});
					}
					async function asyncLoop1(items) {
						for (const item of items) {
							console.log(item)
							await simulateAsyncEvent1(item);
						}
						that.istrue = true
						loading.close()
						that.$message({
							message: '图片上传完成!!',
							type: 'success'
						});
						console.log('图片上传完成')
					}
					asyncLoop1(that.imgArr)
				}
			},
			pictureQuery() {
				let col = uniCloud.importObject('ny102Picture', {
					customUI: true
				})
				col.pictureQuery('黑丝').then(res => {
					console.log(res)
				})
			},
			onSubmits() {
				console.log(this.form)
				console.log(this.dynamicTags)
				let col = uniCloud.importObject('ny102Picture', {
					customUI: true
				})
				let that = this
				if (this.istrue) {
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					});
					console.log(that.imageArr)
					// let num = []
					// that.dynamicTags.map(n => {
					// 	num.push({
					// 		"_id": n._id,
					// 		"name": n.name
					// 	})
					// })
					that.form.type -= 0
					// that.form.tags = num

					function simulateAsyncEvent(item) {
						return new Promise((resolve) => {
							let str = that.form
							let date = new Date().getTime()
							str.img_url = item.img_url
							str.shrink_url = item.shrink_url
							str.create_date = date
							col.addPicture(str).then(res => {
								console.log(res)
								resolve();

							})


						});
					}
					async function asyncLoop(items) {

						for (const item of items) {
							await simulateAsyncEvent(item);
						}
						loading.close();
						that.imgArr = []
						that.shrinkArr = []
						that.istrue = false
						that.$message({
							message: '添加成功!!',
							type: 'success'
						});
					}
					asyncLoop(that.imageArr);


				} else {
					this.$message({
						message: '请先上传图片到服务器!!',
						type: 'warning'
					});

				}
			},
			handleClose(tag) {
				this.form.tags.splice(this.form.tags.indexOf(tag), 1);
			},

			showInput() {
				this.inputVisible = true;
				this.$nextTick(_ => {
					this.$refs.saveTagInput.$refs.input.focus();
				});
			},

			handleInputConfirm() {
				let col = uniCloud.importObject('ny102Tags', {
					customUI: true
				})
				let inputValue = this.inputValue;
				console.log(inputValue)
				if (inputValue) {
					console.log('1111', inputValue)
					col.addTag(inputValue).then((res) => {
						console.log(res)
						if (res.msg == '添加成功') {
							this.form.tags.push({
								"_id": res.data.id,
								"name": inputValue
							});
						} else {
							this.form.tags.push({
								"_id": res.data[0]._id,
								"name": res.data[0].name
							});
						}
					})
					// this.dynamicTags.push(inputValue);
				}
				this.inputVisible = false;
				this.inputValue = '';
			},
			handlePictureCardPreview(file) {
				this.form.shrink_url = file;
				this.dialogVisible = true;
			},
			uploaD(item) {
				let that = this
				uni.chooseImage({
					count: 20,
					sizeType: ['original'],
					success(res) {
						that.imageArr = []
						for (let i = 0; i < res.tempFilePaths.length; i++) {

							let filePath = res.tempFilePaths[i] // 选择图片的临时路径
							let tempFiles = res.tempFiles[i]
							const imgType = tempFiles.type.replace('image/', '').trim()
							let name = 'NY' // 选择图片的名称.后缀名
							// 生成随机名字
							let result = '';
							const characters =
								'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
							for (let i = 0; i < 6; i++) {
								result += characters.charAt(Math.floor(Math.random() * characters.length));
							}
							that.imgArr.push({
								name: `${name}_${result}`,
								url: filePath,
								type: imgType
							})
							that.img_url.name = `${name}_${result}`
							that.img_url.url = filePath
							that.imageArr.push({
								img_url: `https://mp-ab4407e3-0701-45ce-b458-b02edc2d6474.cdn.bspapp.com/ny102/pictureAll/lossless/${name}_${result}.${imgType}`
							})
							var handleImage = function(imgSrc) {
								// 创建一个Image对象
								var img = new Image();
								img.src = imgSrc;
								// 定义图片加载完成时的处理函数
								var onLoadHandler = function() {
									// 移除事件监听器，确保只执行一次
									img.removeEventListener('load', onLoadHandler);
									// 创建一个Canvas元素
									var canvas = document.createElement('canvas');
									var ctx = canvas.getContext('2d');
									// 设置Canvas的尺寸
									var scale = 0.5
									var imgWidth = img.width * scale;
									var imgHeight = img.height * scale;
									canvas.width = imgWidth;
									canvas.height = imgHeight;
									// 在Canvas上绘制图片
									ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
									// 将Canvas中的图片转换为DataURL
									var compressedDataURL = canvas.toDataURL('image/jpeg',
										0.8); // 压缩质量为0.8
									// 调用上传的接口
									that.shrinkArr.push({
										name: `${name}_${result}shrink`,
										url: compressedDataURL
									})
									that.shrink_url.url = compressedDataURL
									that.shrink_url.name = `${name}_${result}shrink`
									that.imageArr[i].shrink_url =
										`https://mp-ab4407e3-0701-45ce-b458-b02edc2d6474.cdn.bspapp.com/ny102/pictureAll/shrinkage/${name}_${result}shrink.jpeg`
									// that.uploadFileImg(compressedDataURL, result)
								}
								// 监听图片加载完成事件
								img.addEventListener('load', onLoadHandler);
							}
							handleImage(filePath);
						}
					}

				});
			},
		},

	}
</script>

<style lang="scss">
	.history {
		width: 180px;
		height: 500px;
		background-color: #c0ccda;
		position: absolute;
		right: 50px;
		top: 100px;
		border-radius: 10px;

		.history-title {
			width: 100%;
			text-align: center;
			font-size: 20px;
			margin: 10px 0;
			height: 30px;
		}

		.history-cont {
			width: 100%;
			height: 430px;
			padding: 10px 0;
			overflow: auto;

			img {
				width: 80%;
				margin-left: 10%;
				margin-bottom: 5px;
			}
		}

		/* 设置滚动条的宽度为10px，并且颜色为红色 */
		.history-cont::-webkit-scrollbar {
			width: 2px;
		}
	}

	.container {
		margin: 0;
		padding: 0;
		background-color: #fff;
		width: 100%;
		height: 90%;
		overflow-y: auto;
		overflow-x: hidden;

		.box-card {
			width: 95%;
			margin: 0 auto;
			margin-top: 10px;
			margin-bottom: 20px;

			.select-tag {
				margin-top: 20px;
				width: 100%;
				min-height: 50px;

				.el-tag+.el-tag {
					margin-left: 10px;
				}

				.button-new-tag {
					margin-left: 10px;
					height: 32px;
					line-height: 30px;
					padding-top: 0;
					padding-bottom: 0;
				}

				.input-new-tag {
					width: 90px;
					margin-left: 10px;
					vertical-align: bottom;
				}
			}

			.ny-card-itam {
				position: relative;
				width: 208px;
				height: 74px;

				image {
					position: absolute;
					width: 100%;
					height: 100%;
				}
			}

			.ny-upload-ul {
				margin: 0;
				display: inline;
				vertical-align: top;

				li {
					overflow: hidden;
					background-color: #fff;
					border: 1px solid #c0ccda;
					border-radius: 6px;
					box-sizing: border-box;
					width: 148px;
					height: 148px;
					margin: 0 8px 8px 0;
					display: inline-block;

					div {
						width: 100%;
						height: 100%;
						display: block;
						unicode-bidi: isolate;
						position: relative;

						img {
							width: 100%;
						}

						.ny-upload-span:hover {
							opacity: 1;
						}

						.ny-upload-span {
							position: absolute;
							width: 100%;
							height: 100%;
							left: 0;
							top: 0;
							cursor: default;
							text-align: center;
							color: #fff;
							opacity: 0;
							font-size: 20px;
							background-color: rgba(0, 0, 0, .5);
							transition: opacity .3s;
							line-height: 148px;

							.ny-upload-span-itam1 {
								cursor: pointer;
								padding: 0 10px;
							}

							.ny-upload-span-itam2 {
								padding: 0 10px;
								cursor: pointer;
							}
						}
					}

				}
			}

			.ny-upload-img {
				display: inline-block;
				background-color: #fbfdff;
				border: 1px dashed #c0ccda;
				border-radius: 6px;
				-webkit-box-sizing: border-box;
				box-sizing: border-box;
				width: 148px;
				height: 148px;
				cursor: pointer;
				line-height: 146px;
				vertical-align: top;
				position: relative;
				text-align: center;
				color: #8c939d;
				font-size: 26px;
			}

			.ny-upload-img:hover {
				border-color: #409EFF;
				color: #409EFF;
			}
		}

	}

	.ny-from-primary {
		width: 99%;
		height: 70px;
		background-color: #fff;
		position: absolute;
		bottom: 0px;
		border-radius: 10px 10px 0 0;

		.ny-from-primary-box {
			margin: 0 auto;
			width: 400px;
			height: 40px;
			margin-top: 15px;
		}
	}
</style>